const qs = require('qs')
const Mock = require('mockjs')
const config = require('../src/utils/config')

const { apiPrefix } = config

let usersListData = Mock.mock({
  'data|80-100': [
    {
      id: '@id',
      name: '@name',
      nickName: '@last',
      phone: /^1[34578]\d{9}$/,
      'age|11-99': 1,
      address: '@county(true)',
      isMale: '@boolean',
      email: '@email',
      createTime: '@datetime',
      avatar() {
        return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.nickName.substr(0, 1))
      },
    },
  ],
})

const depts = [
  {
    id: 1,
    name: "总经办",
    sn: "ZONGJINGBAN:1",
  },
  {
    id: 2,
    name: "技术部",
    sn: "JISHUBU:2",
  },
  {
    id: 3,
    name: "财务部",
    sn: "CAIWUBU:3",
  },
]
const roles = [
  {
    id: 1,
    name: "管理员",
    sn: "admin",
  },
  {
    id: 2,
    name: "销售员",
    sn: "salesman",
  },
  {
    id: 3,
    name: "人事",
    sn: "hr",
  },
]

let tableListDataSource = []
for (let i = 0; i < 46; i += 1) {
  tableListDataSource.push({
    id: i + 1,
    sn: 'sn:'.concat(i, 1),
    username: 'hox'.concat(i),
    realname: '吴彦祖'.concat(i),
    dept: depts[Math.floor(Math.random() * 3)],
    role: roles[Math.floor(Math.random() * 3)],
    phoneNum: '1880810888'.concat(i),
    email: 'hox'.concat(i, '@hooox.io'),
    age: Math.floor(Math.random() * 30),
    gender: Math.floor(Math.random() * 3),
    status: Math.floor(Math.random() * 2),
    birthDay: `1990-03-${Math.floor(i / 2) + 1}`,
    description: 'description '.concat(i),
    lastLoginAt: `2018-08-${Math.floor(i / 2) + 1} ${Math.floor(Math.random() * 12)}:${Math.floor(Math.random() * 60)}:${Math.floor(Math.random() * 60)}`,
    loginCount: Math.floor(Math.random() * 30),
  })
}

let database = usersListData.data

const EnumRoleType = {
  ADMIN: 'admin',
  DEFAULT: 'guest',
  DEVELOPER: 'developer',
}

const userPermission = {
  DEFAULT: {
    visit: ['1'],
    role: EnumRoleType.DEFAULT,
  },
  ADMIN: {
    visit: ['1', '1000', '1001', '1002', '1003', '1004'],
    role: EnumRoleType.ADMIN,
  },
  DEVELOPER: {
    visit: ['1', '1000', '1001'],
    role: EnumRoleType.DEVELOPER,
  },
}

const adminUsers = [
  {
    id: 0,
    username: 'admin',
    password: 'admin',
    permissions: userPermission.ADMIN,
  }, {
    id: 1,
    username: 'guest',
    password: 'guest',
    permissions: userPermission.DEFAULT,
  }, {
    id: 2,
    username: 'hox',
    password: '111111',
    permissions: userPermission.DEVELOPER,
  },
]

const queryArray = (array, key, keyAlias = 'key') => {
  if (!(array instanceof Array)) {
    return null
  }
  let data

  for (let item of array) {
    if (item[keyAlias] === key) {
      data = item
      break
    }
  }

  if (data) {
    return data
  }
  return null
}

const NOTFOUND = {
  message: 'Not Found',
  documentation_url: 'http://localhost:8000/request',
}

module.exports = {

  [`POST ${apiPrefix}/users/login`](req, res) {
    const { username, password } = req.body
    const user = adminUsers.filter(item => item.username === username)

    if (user.length > 0 && user[0].password === password) {
      const now = new Date()
      now.setDate(now.getDate() + 1)
      res.cookie('token', JSON.stringify({ id: user[0].id, deadline: now.getTime() }), {
        maxAge: 900000,
        httpOnly: true,
      })
      res.json({ code: 0, message: 'Ok', data: '700633a1b0f65fa8456a18bd6053193c' })
    } else {
      res.status(400).json({ code: 1011, message: '用户名或密码错误' })
    }
  },

  [`GET ${apiPrefix}/employee/test`](req, res) {
    // res.clearCookie('token')

    res.status(200).json({
      code: 1011,
      message: "用户认证失败，请登录后再访问",
    })
  },

  [`GET ${apiPrefix}/user/logout`](req, res) {
    res.clearCookie('token')
    res.status(200).end()
  },

  [`GET ${apiPrefix}/users`](req, res) {
    const token = req.headers.authentication || ''
    const response = {}
    const user = {}
    if (!token) {
      res.status(200).send({ code: 1010, message: 'Not Login' })
      return
    }
    if (token) {
      response.code = 0
    } else {
      response.code = 1010
    }

    if (response.code === 0) {
      user.permissions = adminUsers[0].permissions
      user.username = adminUsers[0].username
      user.id = adminUsers[0].id
    }
    response.data = user
    res.json(response)
  },

  [`GET ${apiPrefix}/employeess`](req, res) {
    const { query } = req
    let { size, current, ...other } = query
    size = size || 10
    current = current || 1

    let newData = tableListDataSource
    for (let key in other) {
      if (key === 'roleId') {
        other['role'] = { id: other[key] }
        key = "role"
      }
      if ({}.hasOwnProperty.call(other, key)) {
        newData = newData.filter((item) => {
          if ({}.hasOwnProperty.call(item, key)) {
            if (item[key] instanceof Object && other[key] instanceof Object) {
              return (item[key]['id'] + '') === (other[key]['id'] + '')
            }
            return String(item[key]).trim().indexOf(decodeURI(other[key]).trim()) > -1
          }
          return true
        })
      }
    }

    res.status(200).json({
      code: 0,
      message: "successed",
      data: {
        records: newData,
        total: newData.length,
      },
    })
  },

  [`GET ${apiPrefix}/employees/keys/:key`](req, res) {
    res.status(200).json({
      "code": 0,
      "msg": "查询成功",
      "data": [
        {
          "name": "测试1",
          "id": "15"
        },
        {
          "name": "hox1",
          "id": "22"
        },
        {
          "name": "11",
          "id": "25"
        }
      ]
    })
  },

  [`POST ${apiPrefix}/users/delete`](req, res) {
    const { ids } = req.body
    database = database.filter(item => !ids.some(_ => _ === item.id))
    res.status(204).end()
  },


  [`POST ${apiPrefix}/user`](req, res) {
    const newData = req.body
    database.unshift(newData)

    res.status(200).end()
  },

  [`GET ${apiPrefix}/user/:id`](req, res) {
    const { id } = req.params
    const data = queryArray(database, id, 'id')
    if (data) {
      res.status(200).json(data)
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`GET ${apiPrefix}/users/searchEmp`](req, res) {
    const { key } = req.query
    const data = [
      { id: 1, name: key },
      { id: 2, name: key + key },
      { id: 3, name: key + key + key },
    ]
    if (data) {
      res.status(200).json({
        code: 0,
        message: 'success',
        data: data,
      })
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`DELETE ${apiPrefix}/user/:id`](req, res) {
    const { id } = req.params
    const data = queryArray(database, id, 'id')
    if (data) {
      database = database.filter(item => item.id !== id)
      res.status(204).end()
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`PATCH ${apiPrefix}/user/:id`](req, res) {
    const { id } = req.params
    const editItem = req.body
    let isExist = false

    database = database.map((item) => {
      if (item.id === id) {
        isExist = true
        return Object.assign({}, item, editItem)
      }
      return item
    })

    if (isExist) {
      res.status(201).end()
    } else {
      res.status(404).json(NOTFOUND)
    }
  },
}
